<template>
  <div class="mx-auto w-330">
    <validate-form @form-submit="onSubmitForm">
      <div class="form-group mb-3">
        <label>邮箱地址</label>
        <validate-input
          :rules="emailRules"
          v-model="emailVal"
          placeholder="请输入邮箱"
          type="email"
          ref="inputRef"
          inputType="input"
        />
      </div>
      <div class="form-group mb-3">
        <label>密码</label>
        <validate-input
          :rules="passwordRules"
          v-model="passwordVal"
          placeholder="请输入密码"
          type="password"
          inputType="input"
        />
      </div>
      <template #submit>
        <button type="submit" class="btn btn-primary">登录</button>
      </template>
    </validate-form>
  </div>
</template>
<script lang='ts'>
import { defineComponent, reactive, ref } from "vue";
import ValidateInput, { RuleProp } from "../components/ValidateInput.vue";
import ValidateForm from "../components/ValidateForm.vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
import createMessage from "@/utils/createMessage";
export default defineComponent({
  name: "Login",
  components: {
    ValidateInput,
    ValidateForm,
  },
  setup() {
    const emailVal = ref("");
    const passwordVal = ref("");

    // 这里的类型和dropdown里面不一样，设置为any
    const inputRef = ref<any>(null);

    const emailRules: RuleProp[] = [
      {
        type: "required",
        message: "邮箱地址不能为空",
      },
      {
        type: "email",
        message: "请输入正确的邮箱格式",
      },
    ];
    const passwordRules: RuleProp[] = [
      {
        type: "required",
        message: "密码不能为空",
      },
    ];

    // 路由
    const router = useRouter();
    const store = useStore();
    const onSubmitForm = (result: Array<boolean>) => {
      if (result.every((item) => item === true)) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value,
        };
        store
          .dispatch("loginAndFetch", payload)
          .then((data) => {
            console.log("data", data);
            createMessage("登陆成功，即将进入首页", "success");
            router.push("/");
          })
          .catch((e) => {
            console.log(e);
          });
      }
    };
    return {
      emailRules,
      emailVal,
      passwordVal,
      passwordRules,
      onSubmitForm,
      inputRef,
    };
  },
});
</script>
<style scoped>
.w-330 {
  max-width: 330px;
}
</style>